package com.foodcommunity.controller;

import com.foodcommunity.entity.User;
import com.foodcommunity.service.CategoryService;
import com.foodcommunity.service.FoodPostService;
import com.foodcommunity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 管理员控制器
 * 处理管理员相关功能，包括用户管理
 */
@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private FoodPostService foodPostService;
    
    @Autowired
    private CategoryService categoryService;

    /**
     * 用户管理页面
     */
    @GetMapping("/users")
    public String userManagement(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword,
            Model model,
            HttpSession session) {
        
        // 检查是否登录且是管理员
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            return "redirect:/";
        }
        
        // 获取用户列表
        Map<String, Object> result = userService.getUserList(page, size, keyword);
        
        model.addAttribute("users", result.get("users"));
        model.addAttribute("totalPages", result.get("totalPages"));
        model.addAttribute("currentPage", page);
        model.addAttribute("keyword", keyword);
        
        return "admin/user-management";
    }
    
    /**
     * 美食日记管理页面
     */
    @GetMapping("/posts")
    public String postManagement(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword,
            Model model,
            HttpSession session) {
        
        // 检查是否登录且是管理员
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            return "redirect:/";
        }
        
        // 获取美食日记列表
        Map<String, Object> result = foodPostService.getPostList(page, size, keyword);
        
        // 获取所有分类，用于编辑美食日记时选择
        model.addAttribute("categories", categoryService.getAllCategories());
        model.addAttribute("posts", result.get("posts"));
        model.addAttribute("totalPages", result.get("totalPages"));
        model.addAttribute("currentPage", page);
        model.addAttribute("keyword", keyword);
        
        return "admin/food-post-management";
    }
    
        // API相关方法已移至AdminApiController
}